package com.wzd.eduservice.controller;


import com.wzd.baseservice.exceptionHandler.BaseException;
import com.wzd.commonutils.JwtUtils;
import com.wzd.commonutils.R;
import com.wzd.eduservice.entity.CourseCollect;
import com.wzd.eduservice.entity.EduChapter;
import com.wzd.eduservice.service.CourseCollectService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 课程收藏 前端控制器
 * </p>
 *
 * @author wzd
 * @since 2021-06-07
 */
@RestController
@Api(tags = "课程收藏")
@RequestMapping("/eduservice/collect")
public class CourseCollectController {

    @Autowired
    private CourseCollectService courseCollectService;

    @ApiOperation(value = "添加课程收藏")
    @GetMapping("add/{courseId}")
    public R addCollect(@PathVariable String courseId, HttpServletRequest request) {
        String memberIdByJwtToken = JwtUtils.getMemberIdByJwtToken(request);
        if (StringUtils.isEmpty(memberIdByJwtToken)) {
            return R.error().code(28004).message("请登录");
        }
        boolean collect = courseCollectService.isCollect(courseId, memberIdByJwtToken);
        // 如果已经添加则跳过
        if (!collect){
            CourseCollect courseCollect = new CourseCollect();
            courseCollect.setCourseId(courseId);
            courseCollect.setMemberId(memberIdByJwtToken);
            courseCollectService.save(courseCollect);
        }
        return R.ok();
    }

    @ApiOperation(value = "删除课程收藏")
    @DeleteMapping("deleteCollect/{courseId}")
    public R deleteChapter(@ApiParam(name = "courseId", value = "课程id", required = true)
                           @PathVariable String courseId) {
        boolean flag = courseCollectService.removeByCourseId(courseId);
        if (flag) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    @ApiOperation(value = "是否收藏")
    @GetMapping("isCollect/{courseId}")
    public R isCollect(@PathVariable String courseId, HttpServletRequest request) {
        String memberIdByJwtToken = JwtUtils.getMemberIdByJwtToken(request);
        if (StringUtils.isEmpty(memberIdByJwtToken)) {
            return R.error().code(28004).message("请登录");
        }
        boolean collect = courseCollectService.isCollect(courseId, memberIdByJwtToken);
        if (collect){
            return R.ok();
        }else {
            return R.error();
        }
    }
}

